<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { userApi } from '@/api'

const router = useRouter()

// 用户列表数据
const users = ref([])

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pages: 0
})

// 加载状态
const loading = ref(false)

// 错误信息
const errorMsg = ref('')

// 获取用户列表
async function fetchUsers(page = 1) {
  loading.value = true
  errorMsg.value = ''
  console.log('开始获取用户列表，页码：', page)
  
  try {
    const res = await userApi.getUsers(page, pagination.size)
    console.log('获取用户列表成功：', res)
    
    if (res.data && Array.isArray(res.data.list)) {
      users.value = res.data.list
      console.log('用户列表数据：', users.value)
      // 调试：检查第一个用户的数据结构
      if (users.value.length > 0) {
        console.log('第一个用户的完整数据：', JSON.stringify(users.value[0], null, 2))
        console.log('用户字段：', Object.keys(users.value[0]))
      }
      
      // 更新分页信息
      pagination.current = res.data.current || res.data.pageNum || page
      pagination.total = res.data.total || 0
      pagination.pages = res.data.pages || Math.ceil((res.data.total || 0) / pagination.size)
      console.log('分页信息：', pagination)
      console.log('API返回的原始分页数据：', {
        current: res.data.current,
        pageNum: res.data.pageNum,
        total: res.data.total,
        pages: res.data.pages,
        size: res.data.size
      })
    } else {
      console.error('返回的数据格式不正确：', res.data)
      errorMsg.value = '获取用户列表失败: 返回的数据格式不正确'
      users.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败：', error)
    errorMsg.value = '获取用户列表失败: ' + (error.message || '未知错误')
    users.value = []
  } finally {
    loading.value = false
  }
}

// 页码变化处理
function handlePageChange(page) {
  fetchUsers(page)
}

// 生成页码数组
function getPageNumbers() {
  const pages = []
  const current = pagination.current
  const total = pagination.pages
  
  if (total <= 7) {
    // 总页数小于等于7，显示所有页码
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 总页数大于7，显示部分页码
    if (current <= 4) {
      // 当前页在前面
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      // 当前页在后面
      pages.push(1)
      pages.push('...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间
      pages.push(1)
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }
  
  return pages
}

// 编辑用户
function editUser(user) {
  console.log('编辑用户：', user)
  // 跳转到用户编辑页面
  router.push(`/dashboard/user/edit/${user.id}`)
}

// 删除用户
async function deleteUser(id) {
  console.log('删除用户ID：', id)
  if (!confirm('确定要删除此用户吗？')) {
    return
  }
  
  try {
    const res = await userApi.deleteUser(id)
    console.log('删除用户成功：', res)
    alert('删除用户成功')
    // 重新加载用户列表
    fetchUsers(pagination.current)
  } catch (error) {
    console.error('删除用户失败：', error)
    alert('删除用户失败: ' + (error.message || '未知错误'))
  }
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMsg" class="error-message">
      {{ errorMsg }}
    </div>
    
    <!-- 加载中 -->
    <div v-if="loading" class="loading-spinner">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 用户列表 -->
    <div v-else-if="users.length > 0" class="user-list">
      <table class="user-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>手机号</th>
            <th>角色</th>
            <th>状态</th>
            <th>注册时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td><span>{{ user.id }}</span></td>
            <td><span>{{ user.username }}</span></td>
            <td><span>{{ user.email || '-' }}</span></td>
            <td><span>{{ user.phone || '-' }}</span></td>
            <td>
              <span :class="['role-badge', user.role === 'admin' ? 'admin' : 'user']">
                {{ user.role === 'admin' ? '管理员' : '普通用户' }}
              </span>
            </td>
            <td>
              <span :class="['status-badge', user.status === 1 ? 'active' : 'inactive']">
                {{ user.status === 1 ? '正常' : '禁用' }}
              </span>
            </td>
            <td><span>{{ user.createTime ? new Date(user.createTime).toLocaleString() : '-' }}</span></td>
            <td class="actions">
              <button class="action-btn edit" @click="editUser(user)">编辑</button>
              <button class="action-btn delete" @click="deleteUser(user.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- 分页 -->
      <div v-if="pagination.total > 0" class="pagination">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ pagination.pages }} 页
        </div>
        
        <div class="pagination-controls">
          <button 
            :disabled="pagination.current === 1" 
            @click="handlePageChange(1)" 
            class="page-btn"
          >
            首页
          </button>
          
          <button 
            :disabled="pagination.current === 1" 
            @click="handlePageChange(pagination.current - 1)" 
            class="page-btn"
          >
            上一页
          </button>
          
          <!-- 页码按钮 -->
          <template v-for="page in getPageNumbers()" :key="page">
            <button 
              v-if="page !== '...'" 
              :class="['page-btn', { 'active': page === pagination.current }]"
              @click="handlePageChange(page)"
            >
              {{ page }}
            </button>
            <span v-else class="page-ellipsis">...</span>
          </template>
          
          <button 
            :disabled="pagination.current === pagination.pages" 
            @click="handlePageChange(pagination.current + 1)" 
            class="page-btn"
          >
            下一页
          </button>
          
          <button 
            :disabled="pagination.current === pagination.pages" 
            @click="handlePageChange(pagination.pages)" 
            class="page-btn"
          >
            末页
          </button>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <p>暂无用户数据</p>
    </div>
  </div>
</template>

<style scoped>
.user-management {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

h2 {
  margin: 0;
  color: #333;
}

.error-message {
  background-color: #ffebee;
  color: #d32f2f;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.user-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.user-table th,
.user-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.user-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.user-table tr:hover {
  background-color: #f5f5f5;
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.action-btn.edit {
  background-color: #4caf50;
  color: white;
}

.action-btn.edit:hover {
  background-color: #43a047;
}

.action-btn.delete {
  background-color: #f44336;
  color: white;
}

.action-btn.delete:hover {
  background-color: #e53935;
}
.user-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #333;
}

.user-table tr:hover {
  background-color: #f9f9f9;
}

.role-badge,
.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.role-badge.admin {
  background-color: #e3f2fd;
  color: #1976d2;
}

.role-badge.user {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-badge.active {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-badge.inactive {
  background-color: #ffebee;
  color: #f44336;
}

.pagination {
  margin-top: 30px;
  text-align: center;
}

.pagination-info {
  margin-bottom: 15px;
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background-color: #fff;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
  font-size: 14px;
  min-width: 40px;
}

.page-btn:hover:not(:disabled) {
  background-color: #f5f5f5;
  border-color: #4CAF50;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn.active {
  background-color: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.page-ellipsis {
  padding: 8px 4px;
  color: #999;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

/* 表格内容样式 */
.user-table td span {
  display: inline-block;
  color: #333;
  font-size: 14px;
  line-height: 1.4;
}

.user-table td {
  vertical-align: middle;
}
</style>